package com.cloudbroker.bcs.common.datasource;

import java.sql.SQLFeatureNotSupportedException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import org.apache.commons.lang3.StringUtils;

import com.cloudbroker.bcs.common.configure.ConfigUtil;
import com.cloudbroker.bcs.common.configure.TenantConfig;
import com.cloudbroker.bcs.common.context.DataContext;

public class TenantIdMappingDataSource extends NameMappingDataSource {
    
    public static final String PROP_KEY_PREFIX = "db.";
    
    @Override
    protected Map<String, Object> getPropsMap(String sourceName) {
        if (null == dsPropsMap) {
            dsPropsMap = new HashMap<String, Map<String, Object>>();
        }
        Map<String, Object> propsMap = dsPropsMap.get(sourceName);
        if (null == propsMap) {
            propsMap = loadPropsMap(sourceName);
            dsPropsMap.put(sourceName, propsMap);
        }
        return propsMap;
    }
    
    protected Map<String, Object> loadPropsMap(String sourceName) {
        Map<String, Object> propsMap = new HashMap<String, Object>();
        // 获取对应的配置集
        TenantConfig tenantConfig = ConfigUtil.getTenantConfig(sourceName);
        
        valuePropsMap(propsMap, PROP_KEY_DRIVERCLASSNAME, tenantConfig);
        String url = tenantConfig.get(PROP_KEY_PREFIX + PROP_KEY_URL);
        if (StringUtils.isBlank(url)) {
            throw new RuntimeException("undefined sourceName " + sourceName);
        }
        propsMap.put(PROP_KEY_URL, url);
        valuePropsMap(propsMap, PROP_KEY_USERNAME, tenantConfig);
        valuePropsMap(propsMap, PROP_KEY_PASSWORD, tenantConfig);
        valuePropsMap(propsMap, PROP_KEY_MAXACTIVE, tenantConfig);
        valuePropsMap(propsMap, PROP_KEY_INITIALSIZE, tenantConfig);
        valuePropsMap(propsMap, PROP_KEY_MAXWAIT, tenantConfig);
        valuePropsMap(propsMap, PROP_KEY_MAXIDLE, tenantConfig);
        valuePropsMap(propsMap, PROP_KEY_MINIDLE, tenantConfig);
        valuePropsMap(propsMap, PROP_KEY_REMOVEABANDONED, tenantConfig);
        valuePropsMap(propsMap, PROP_KEY_REMOVEABANDONEDTIMEOUT, tenantConfig);
        valuePropsMap(propsMap, PROP_KEY_TIMEBETWEENEVICTIONRUNSMILLS, tenantConfig);
        valuePropsMap(propsMap, PROP_KEY_MINEVICTABLEIDLETIMEMILLIS, tenantConfig);
        valuePropsMap(propsMap, PROP_KEY_CONNECTIONPROPERTIES, tenantConfig);
        return propsMap;
    }
    
    private void valuePropsMap(Map<String, Object> propsMap, String key, TenantConfig tenantConfig) {
        propsMap.put(key, tenantConfig.get(PROP_KEY_PREFIX + key));
    }
    
    @Override
    protected String getDataSourceKey() {
        return DataContext.getTenantId();
    }
    
    public static String getRequiredKey() {
        return PROP_KEY_PREFIX + PROP_KEY_URL;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }
}
